package com.oppo.MarkBook.processor;

import com.intellij.ide.fileTemplates.impl.UrlUtil;
import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

/**
 * @author steve
 * @since 2021-12-19 10:08
 */

public class MDFreeMarkProcessor extends AbstractFreeMarkProcessor {
    @Override
    protected Template getTemplate() throws IOException {
        // 加载模板字符串
        String templateContent = UrlUtil.loadText(MDFreeMarkProcessor.class.getResource("/template/md.ftl"));
        // 创建模板配置
        Configuration configuration = new Configuration(Configuration.VERSION_2_3_28);
        // 创建字符串模板的导入器
        StringTemplateLoader templateLoader = new StringTemplateLoader();
        // 导入字符串模板
        templateLoader.putTemplate("MDTemplate",templateContent);
        configuration.setTemplateLoader(templateLoader);
        // 获取模板
        return configuration.getTemplate("MDTemplate");
    }

    @Override
    protected Object getModel(SourceNoteData sourceNoteData) {
        Map<String,Object> modelMap = new HashMap<>();
        // topic 对应 md.ftl 的 topic
        modelMap.put("topic", sourceNoteData.getTopic());
        // noteList 对应md.ftl的 noteList
        modelMap.put("noteList", sourceNoteData.getNoteList());
        return modelMap;
    }

    @Override
    protected Writer getWriter(SourceNoteData sourceNoteData) throws Exception {
        String fileName = sourceNoteData.getFileName();
        File file = new File(fileName);
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
        return bufferedWriter;
    }
}
